package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 利用aop 对控制器增强
 * 处理控制器出现的异常
 */
@ControllerAdvice
public class HandlerControllerException {

    /**
     * @ExceptionHandler代表当前的方法是处理异常，处理什么异常
     *
     * HandlerMethod 代表出现异常的处理方法
     */
    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(RuntimeException e, HttpServletResponse response, HandlerMethod method){
        e.printStackTrace(); //方便开发找bug
        //判断有没有贴ResponseBody注解
        if(method.hasMethodAnnotation(ResponseBody.class)){
            String errorMsg = "操作失败，请联系管理员";
            if(e instanceof LogicException){ //判断是否逻辑异常，如果是，直接用异常自己的错误信息
                errorMsg = e.getMessage();
            }
            JsonResult json = new JsonResult(false, errorMsg);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            return "common/error";
        }
    }

    /**
     * 捕获shiro的没有授权的异常
     * @param e
     * @param response
     * @param method
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerException1(UnauthorizedException e, HttpServletResponse response, HandlerMethod method){
        e.printStackTrace(); //方便开发找bug
        //判断有没有贴ResponseBody注解
        if(method.hasMethodAnnotation(ResponseBody.class)){
            JsonResult json = new JsonResult(false, "你没有权限操作!");
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }else {
            return "common/nopermission";
        }
    }

}
